const userModel = require("../../models/wechat/user");
const { wechatConfig } = require('../../config/index');
const axios = require("axios");

module.exports = {
  async login(req, res) {
    try {
      const { code } = req.body;

      const wxResult = await axios({
        url: 'https://api.weixin.qq.com/sns/jscode2session',
        method: 'GET',
        params: {
          appid: wechatConfig.appid,
          secret: wechatConfig.appsecret,
          js_code: code,
          grant_type: 'authorization_code'
        }
      });

      if (wxResult.status == 200) {
        console.log('微信服务器返回.success', wxResult.data);
        const openid = wxResult.data.openid;

        if (!openid) {
          return res.json({
            code: '1001',
            msg: 'openid不存在'
          })
        }

        const checkUserRes = await userModel.checkUser(openid);
        console.log('查询用户是否存在：', checkUserRes);

        if (checkUserRes.length > 0) {
          console.log('存在用户：')
        } else {
          console.log('不存在用户：')
          const loginRes = await userModel.login(openid);
          console.log('用户写入用户表：', loginRes);
        }


        res.json({
          code: 200,
          msg: 'ok',
          data: {
            openid: wxResult.data.openid
          }
        })
      }
    } catch (err) {
      console.log('用户login失败：', err);
      res.json({
        code: 1001,
        msg: 'fail'
      })
    }
  }
};
